package com.yfbao.horizon.schedule.tk.job;


import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
@Component
public class LockTestJob {

    private Random random =new Random();
    private Object object =new Object();

    @Scheduled(cron="0/15 * * * * ?")
    public void reentrantLockTest(){
        long currentTimeMillis = System.currentTimeMillis();
        Lock lock =new ReentrantLock();
        boolean locked =false;
        try {
            locked = lock.tryLock(100, TimeUnit.MILLISECONDS);
            if(locked){
                int sleepTime = random.nextInt(12);
                log.info("begin do reentrantLockTest job:"+sleepTime);
                Thread.sleep(sleepTime*1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if(locked){
                lock.unlock();
            }
        }
    }


    @Scheduled(cron="0/15 * * * * ?")
    public void sunchronizedLockTest(){
        long currentTimeMillis = System.currentTimeMillis();
        Lock lock =new ReentrantLock();
        boolean locked =false;
        synchronized (object){
            int sleepTime = random.nextInt(12);
            log.info("begin do sunchronizedLockTest job:"+sleepTime);
            try {
                Thread.sleep(sleepTime*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
